package com.learn.activiti.condition;

import com.learn.activiti.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * 判断多实例任务的完成条件
 *
 * @author xianglujun
 * @date 2019/7/12 10:03
 */
@Slf4j
@Service("completeCondition")
public class IdeaCompleteCondition implements Serializable {

    public boolean complete(DelegateExecution execution) {

        log.info("ideaCompleteCondition start...");

        // 获取关于实例的相关变量

        // 1. 实例的总个数
        int nrOfInstances = (int) execution.getVariable(Constants.NR_OF_INSTANCES);

        // 2. 获取未完成的数量
        int nrOfActiveInstances = (int) execution.getVariable(Constants.NR_OF_ACTIVE_INSTANCE);

        // 3. 获取已完成的数量
        int nrOfCompletedInstances = (int) execution.getVariable(Constants.NR_OF_COMPLATED_INSTANCES);

        log.info("multi instances: all:{}, com:{}, act:{}", nrOfInstances, nrOfCompletedInstances, nrOfActiveInstances);

        log.info("result: reject:{},agress:{}", execution.getVariable("rejectCount"),
                execution.getVariable("agreeCount"));

        log.info("audit finished..");
        execution.setVariable("auditPass", true);

        // 获取整体的判断结果
        if (execution.getVariable("rejectCount") != null) {
            int rejectCount = (int) execution.getVariable("rejectCount");
            if (rejectCount > 0) {
                log.info("accor user task has been rejected: {}", rejectCount);
                execution.setVariable("auditPass", false);
                return true;
            }
        }

        // 如果没有人绝句，判断节点是否已经审核完毕
        if (nrOfActiveInstances > 0) {
            log.info("ideaCompleteCondition continue..");
            return false;
        }

        log.info("ideaCompleteCondition end...");
        return true;
    }
}
